<template>
  <div class="written-result-container">
    <div class="page-header">
      <a-button type="text" @click="goBack" style="margin-right: 16px">
        <template #icon><arrow-left-outlined /></template>
        返回
      </a-button>
    </div>
    <a-layout>
      <a-layout-content class="result-content">
        <!-- 加载中 -->
        <div v-if="isLoading" style="text-align: center; margin-top: 100px">
          <a-spin size="large" tip="加载中..." />
        </div>
        <!-- 有考试结果时显示 -->
        <div class="result-wrapper" v-else-if="apiData">
          <a-card class="result-card">
            <template #title>
              <div class="result-header">
                <h2>笔试完成</h2>
                <a-tag color="blue">分析报告</a-tag>
              </div>
            </template>

            <div class="result-info">
              <div class="position-info">
                <h3>笔试分析</h3>
                <p>
                  总分：{{ totalScore }}分，选择题：{{ choiceScore }}分，问答题：{{
                    shortAnswerScore
                  }}分，编程题：{{ programmingScore }}分
                </p>
              </div>

              <div class="score-overview">
                <div class="total-score">
                  <a-progress
                    type="circle"
                    :percent="scorePercent"
                    :format="() => scoreDisplay"
                    :width="120"
                  />
                </div>

                <div class="score-details">
                  <div class="score-item">
                    <span class="label">选择题</span>
                    <span class="value">{{ choiceScore }}/{{ choiceCount * 2 }}分</span>
                    <a-progress
                      :percent="
                        choiceCount === 0
                          ? 0
                          : parseFloat(((choiceScore / (choiceCount * 1.0 * 2)) * 100).toFixed(2))
                      "
                      status="active"
                    />
                  </div>

                  <div class="score-item">
                    <span class="label">问答题</span>
                    <span class="value">{{ shortAnswerScore }}/{{ shortAnswerCount * 10 }}分</span>
                    <a-progress
                      :percent="
                        shortAnswerCount === 0
                          ? 0
                          : parseFloat(
                              ((shortAnswerScore / (shortAnswerCount * 1.0 * 10)) * 100).toFixed(2)
                            )
                      "
                      status="active"
                    />
                  </div>

                  <div class="score-item" v-if="programmingList.length">
                    <span class="label">编程题评价</span>
                    <span class="value">{{ programmingScore }}/{{ programmingCount * 10 }}分</span>
                    <a-progress
                      :percent="
                        programmingCount === 0
                          ? 0
                          : parseFloat(
                              ((programmingScore / (programmingCount * 1.0 * 10)) * 100).toFixed(2)
                            )
                      "
                      status="active"
                    />
                  </div>
                </div>
              </div>
            </div>

            <!-- 自动批改部分 -->
            <div class="evaluation-section">
              <a-divider>
                <span class="divider-title">自动批改结果</span>
              </a-divider>

              <div class="evaluation-tabs">
                <a-tabs>
                  <a-tab-pane key="choice" tab="选择题评分">
                    <div class="choice-results">
                      <a-table
                        :dataSource="formattedChoiceResults"
                        :pagination="false"
                        :rowClassName="(record) => (record.correct ? 'correct-row' : 'wrong-row')"
                      >
                        <a-table-column title="题号" dataIndex="index" width="60px" />
                        <a-table-column title="题目" dataIndex="title" />
                        <a-table-column title="你的答案" dataIndex="userAnswer" width="120px" />
                        <a-table-column title="正确答案" dataIndex="correctAnswer" width="120px" />
                        <a-table-column
                          title="结果"
                          dataIndex="correct"
                          width="80px"
                          :customRender="
                            ({ text }) => {
                              return text
                                ? h('span', { style: { color: '#52c41a' } }, '正确')
                                : h('span', { style: { color: '#f5222d' } }, '错误')
                            }
                          "
                        />
                      </a-table>
                    </div>
                  </a-tab-pane>

                  <a-tab-pane key="essay" tab="问答题评价">
                    <div class="essay-results">
                      <a-collapse>
                        <a-collapse-panel
                          v-for="(result, index) in formattedEssayResults"
                          :key="index"
                          :header="'问题 ' + (index + 1) + ': ' + result.title.slice(0, 30) + '...'"
                        >
                          <div class="essay-item">
                            <div class="essay-question">
                              <h4 style="color: #2a6dd5">问题：</h4>
                              <p v-html="result.title"></p>
                            </div>

                            <div class="essay-answer">
                              <h4 style="color: #2a6dd5">你的回答：</h4>
                              <p class="answer-content" v-html="result.answer"></p>
                            </div>

                            <div class="essay-evaluation">
                              <h4>
                                评分：<span class="essay-score">{{ result.score }} / 10</span>
                              </h4>

                              <div class="reference-answer">
                                <h4 style="color: #2a6dd5">参考答案：</h4>
                                <p v-html="result.referenceAnswer"></p>
                              </div>
                            </div>
                          </div>
                        </a-collapse-panel>
                      </a-collapse>
                    </div>
                  </a-tab-pane>

                  <a-tab-pane key="programming" tab="编程题分析" v-if="programmingList.length">
                    <div class="programming-results">
                      <a-collapse>
                        <a-collapse-panel
                          v-for="(result, index) in formattedProgrammingResults"
                          :key="index"
                          :header="index + 1 + '. ' + result.title.slice(0, 30) + '...'"
                        >
                          <div class="programming-item">
                            <div class="programming-question">
                              <h4 style="color: #2a6dd5">题目：</h4>
                              <p v-html="result.title"></p>
                            </div>
                            <div class="programming-answer">
                              <h4 style="color: #2a6dd5">你的代码：</h4>
                              <OnlyReadCodeEditor
                                :language="result.userAnswerLanguage"
                                :value="result.userAnswer"
                              />
                            </div>
                            <div class="programming-correct-answer">
                              <h4 style="color: #2a6dd5">参考答案：</h4>
                              <OnlyReadCodeEditor
                                :language="result.correctAnswerLanguage"
                                :value="result.correctAnswer"
                              />
                            </div>

                            <div
                              class="programming-explanations"
                              v-if="result.explanations && result.explanations.length > 0"
                            >
                              <h4 style="color: #2a6dd5">
                                <span class="explanation-header">
                                  <book-outlined /> 题目讲解资源
                                </span>
                                <span class="explanation-count"
                                  >共 {{ result.explanations.length }} 个资源</span
                                >
                              </h4>
                              <div class="explanation-links">
                                <a-row :gutter="[16, 16]">
                                  <a-col
                                    :xs="24"
                                    :sm="24"
                                    :md="12"
                                    v-for="(link, linkIndex) in result.explanations"
                                    :key="linkIndex"
                                  >
                                    <a-card class="link-card" hoverable @click="openLink(link.url)">
                                      <template #title>
                                        <div class="link-title">
                                          <span>{{ linkIndex + 1 }}. {{ link.name }}</span>
                                        </div>
                                      </template>
                                      <template #extra>
                                        <a-button type="link" @click.stop="openLink(link.url)">
                                          <template #icon><link-outlined /></template>
                                          访问
                                        </a-button>
                                      </template>
                                      <div class="link-url"><global-outlined /> {{ link.url }}</div>
                                    </a-card>
                                  </a-col>
                                </a-row>
                              </div>
                            </div>
                          </div>
                        </a-collapse-panel>
                      </a-collapse>
                    </div>
                  </a-tab-pane>
                </a-tabs>
              </div>
            </div>

            <div class="action-buttons">
              <a-button @click="goBack">返回笔试页面</a-button>
              <a-button type="primary" @click="goToRecords">查看历史记录</a-button>
            </div>
          </a-card>
        </div>
        <!-- 无考试结果时显示 -->
        <div class="no-result" v-else>
          <a-card>
            <a-empty description="当前没有笔试分析结果" />
          </a-card>
        </div>
      </a-layout-content>
    </a-layout>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ArrowLeftOutlined,
  LinkOutlined,
  BookOutlined,
  GlobalOutlined,
} from '@ant-design/icons-vue'
import {
  getExamAnalyzeResultUsingGet,
  getPartQuestionCountUsingGet,
  getWrongProgramingInfoUsingGet,
} from '@/api/examController'
import hljs from 'highlight.js/lib/core'
import java from 'highlight.js/lib/languages/java'
import python from 'highlight.js/lib/languages/python'
import cpp from 'highlight.js/lib/languages/cpp'
import javascript from 'highlight.js/lib/languages/javascript'
import 'highlight.js/styles/github.css'
import OnlyReadCodeEditor from '@/components/OnlyReadCodeEditor.vue'
import { detectLanguage } from '@/utils/DetectionCodelanguage'

hljs.registerLanguage('java', java)
hljs.registerLanguage('python', python)
hljs.registerLanguage('cpp', cpp)
hljs.registerLanguage('javascript', javascript)

const router = useRouter()
const route = useRoute()
const examId = route.query.examId // 从url中获取查询参数
const apiData = ref(null)
const isLoading = ref(true)
//选择题数量
const choiceCount = ref(0)
//问答题数量
const shortAnswerCount = ref(0)
//编程题数量
const programmingCount = ref(0)

// 选择题、问答题、编程题数据
//选择题错题
const choiceList = computed(() => apiData.value?.choices?.list || [])
//选择题分数
const choiceScore = computed(() => apiData.value?.choices?.totalScore ?? 0)

//问答题题目
const shortAnswerList = computed(() => apiData.value?.shortAnswers?.list || [])
//问答题分数
const shortAnswerScore = computed(() => apiData.value?.shortAnswers?.totalScore ?? 0)

//编程题题目
const programmingList = computed(() => apiData.value?.programmings?.list || [])
//编程题分数
const programmingScore = computed(() => apiData.value?.programmings?.totalScore ?? 0)

//总数
const totalScore = computed(
  () => choiceScore.value + shortAnswerScore.value + programmingScore.value
)
const scorePercent = computed(() => Math.round((totalScore.value / 100) * 100))
const scoreDisplay = computed(() => `${totalScore.value}分`)

// 格式化 选择题结果
const formattedChoiceResults = computed(() => {
  return choiceList.value.map((item, index) => {
    const correct = item.user_answer === item.correct_answer
    return {
      index: index + 1,
      title: item.questionTitle,
      userAnswer: item.user_answer_content || item.user_answer || '未作答',
      correctAnswer: item.correct_answer_content || item.correct_answer || '',
      correct,
    }
  })
})

// 格式化 问答题结果
const formattedEssayResults = computed(() => {
  return shortAnswerList.value.map((item, index) => {
    return {
      index: index + 1,
      title: item.questionTitle,
      answer: item.user_answer || '未作答',
      referenceAnswer: item.correct_answer || '',
      score: item.score,
      comments: '',
    }
  })
})

/**
 * 获取错误编程题信息
 */
const fetchWrongProgramingInfo = async () => {
  const data = await getWrongProgramingInfoUsingGet({
    examId: examId as any,
  })
  explanationLinks.value = data.data as any
}

// 存储编程题解释链接
const explanationLinks = ref<any[]>([])

// 格式化 编程题结果
const formattedProgrammingResults = computed(() => {
  return programmingList.value.map((item, index) => {
    // 编程题暂不评分
    return {
      index: index + 1,
      title: item.questionTitle,
      userAnswer: item.user_answer || '未作答',
      userAnswerLanguage: detectLanguage(item.user_answer),
      correctAnswer: item.correct_answer || '',
      correctAnswerLanguage: detectLanguage(item.correct_answer),
      explanations: explanationLinks.value[index] || [],
    }
  })
})

// 返回笔试页面
const goBack = () => {
  router.go(-1)
}

// 查看历史记录
const goToRecords = () => {
  router.push('/written/records')
}

// 打开外部链接
const openLink = (url: string) => {
  window.open(url, '_blank')
}

/**
 * 获取笔试分析结果
 */
const fetchExamResult = async () => {
  //发送请求获取笔试分析结果
  const data = await getExamAnalyzeResultUsingGet({
    examId: examId as any,
  })
  console.log(data.data)
  if (data && data.code === 0 && data.data) {
    apiData.value = data.data as any
  }
}

/**
 * 获取各部分题目
 */
const getQuestionCount = async () => {
  const data = await getPartQuestionCountUsingGet({
    examId: examId as any,
  })
  choiceCount.value = data.data.choiceCount
  shortAnswerCount.value = data.data.shortAnswerCount
  programmingCount.value = data.data.programmingCount
}

onMounted(async () => {
  isLoading.value = true
  //获取各部分题目
  await getQuestionCount()
  //获取笔试分析结果
  await fetchExamResult()
  //获取错误编程题信息
  if (apiData.value) {
    await fetchWrongProgramingInfo()
  }
  isLoading.value = false
})
</script>

<style scoped>
.written-result-container {
  height: 100%;
  min-height: 100vh;
  background-color: #f0f2f5;
  padding: 24px;
}

.result-content {
  margin: 0 auto;
  overflow-y: auto;
  width: 1400px;
}

.result-wrapper {
  padding-bottom: 24px;
}

.no-result {
  margin-top: 100px;
  text-align: center;
}

.result-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.result-header h2 {
  margin: 0;
  color: #1890ff;
}

.result-info {
  margin-bottom: 24px;
}

.position-info {
  margin-bottom: 16px;
}

.position-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.position-info p {
  margin: 0;
  color: #666;
}

.score-overview {
  display: flex;
  margin-top: 24px;
  background-color: #f9f9f9;
  padding: 16px;
  border-radius: 8px;
}

.total-score {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-right: 24px;
  margin-right: 24px;
  border-right: 1px solid #eee;
}

.score-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 12px;
}

.score-item {
  display: flex;
  flex-direction: column;
}

.label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.value {
  font-weight: 500;
  margin-bottom: 4px;
}

.divider-title {
  font-weight: 500;
  color: #1890ff;
}

.evaluation-section {
  margin-top: 32px;
}

.evaluation-tabs {
  margin-top: 16px;
}

.choice-results {
  margin-top: 16px;
}

:deep(.correct-row) {
  background-color: #f6ffed;
}

:deep(.wrong-row) {
  background-color: #fff1f0;
}

.essay-item {
  padding: 16px;
}

.essay-question,
.essay-answer,
.essay-evaluation {
  margin-bottom: 16px;
}

.essay-question h4,
.essay-answer h4,
.essay-evaluation h4,
.essay-comments h4,
.reference-answer h4 {
  margin-top: 0;
  margin-bottom: 8px;
  font-weight: 500;
}

.answer-content {
  white-space: pre-line;
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  min-height: 60px;
}

.essay-score {
  color: #1890ff;
  font-weight: bold;
}

.comment-content {
  background-color: #fffbe6;
  padding: 12px;
  border-radius: 4px;
  border-left: 4px solid #faad14;
}

.reference-answer {
  margin-top: 16px;
  background-color: #f0f5ff;
  padding: 12px;
  border-radius: 4px;
  border-left: 4px solid #1890ff;
}

.action-buttons {
  margin-top: 32px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.programming-explanations {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px dashed #e8e8e8;
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.explanation-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.explanation-count {
  margin-left: 12px;
  font-size: 14px;
  color: #888;
  font-weight: normal;
}

.explanation-links {
  margin-top: 16px;
}

.link-card {
  height: 100%;
  transition: all 0.3s;
  border: 1px solid #e8e8e8;
  overflow: hidden;
  background: linear-gradient(135deg, #ffffff 0%, #f9fafc 100%);
}

.link-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.1);
  border-color: #1890ff;
}

.link-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
  color: #1890ff;
}

.link-url {
  color: #888;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #f0f0f0;
  display: flex;
  align-items: center;
  gap: 4px;
}

.programming-item {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.programming-question,
.programming-answer,
.programming-correct-answer {
  margin-bottom: 0;
}
</style>
